import {
  addStaff,
  delStaff,
  queryStafflist,
  updateStaff,
} from "@/services/employeeManagement";
import { uploadUrl } from "@/untils";
import {
  DrawerForm,
  ProFormDatePicker,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Form, message, Popconfirm, Tag } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
export const imgConfig = {
  url: "http://admin.lianhongtech.com/uploads/",
};

const EmployeeInfoForm = () => {
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [currentType, setCurrentType] = useState<string>("");
  const actionRef: any = useRef(null);
  const [currentData, setCurrentData] = useState<any>(null); // 当前数据
  const [fileList, setFileList] = useState<any>([]); // 身份证正反面
  const handleDel = async (id: number) => {
    const res = await delStaff({ id });
    if (res?.success) {
      message.success("操作成功");
      setOpen(false);
      actionRef?.current?.reload();
    } else {
      message.error("操作失败，请联系管理员");
    }
  };
  // 员工信息表列配置
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      width: 100,
      fixed: "left",
      formItemProps: { rules: [{ required: true }] },
    },
    {
      title: "性别",
      dataIndex: "sex",
      key: "sex",
      width: 80,
      search: false,
      valueEnum: { 1: "男", 2: "女" },
    },
    {
      title: "身份证号",
      dataIndex: "idcard",
      key: "idcard",
      width: 180,
      search: false,
      formItemProps: { rules: [{ len: 18, message: "请输入18位身份证号" }] },
    },
    {
      title: "职位",
      dataIndex: "position",
      search: false,
      key: "position",
      width: 120,
      render: (text: string) => <Tag color="cyan">{text}</Tag>,
    },
    {
      title: "入职日期",
      dataIndex: "onboard_time",
      key: "onboard_time",
      search: false,
      width: 120,
      render: (time: string) => dayjs(Number(time) * 1000).format("YYYY-MM-DD"),
    },
    {
      title: "联系电话",
      dataIndex: "phone",
      search: false,
      key: "phone",
      width: 130,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      search: false,
      fixed: "right",
      valueEnum: {
        0: { text: "离职", status: "Warning" },
        1: { text: "在职", status: "Success" },
      },
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      search: false,
      fixed: "right",
      render: (_: any, record: any) => (
        <>
          <a onClick={() => handleEdit(record)}>编辑</a>
          <span style={{ margin: "0 8px", color: "#eee" }}>|</span>
          <a onClick={() => handleViewDetail(record)}>详情</a>
          <span style={{ margin: "0 8px", color: "#eee" }}>|</span>
          <Popconfirm
            title="提示"
            description="确认删除该员工吗？"
            onConfirm={() => handleDel(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <a style={{ marginRight: 8 }}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  // 请求批次列表
  const getStafflist = async (values: any) => {
    const res = await queryStafflist({
      page: values?.current,
      pagesize: 10,
      name: values?.name,
    });
    return {
      data: res?.result?.data,
      total: res?.result?.total,
      success: true,
    };
  };

  useEffect(() => {
    if (open && currentType !== "create") {
      const {
        id,
        idcard,
        name,
        onboard_time,
        phone,
        position,
        status,
        sex,
        idcardpics,
      } = currentData;
      const picList = idcardpics?.length
        ? idcardpics?.split(",")?.map((v: any) => imgConfig?.url + v)
        : [];
      const list1 = picList.map((url, i) => ({
        uid: `-${i}`,
        url,
        name: `img_${i}`,
        status: "done",
      }));
      form.setFieldsValue({
        id,
        idcard,
        name,
        phone,
        status,
        sex,
        onboard_time: dayjs(onboard_time * 1000).format("YYYY-MM-DD"),
        position: position?.split(","),
        idcardpics: list1,
      });
      setFileList(list1);
    } else {
      form.resetFields();
    }
  }, [open, currentData, currentType]);
  const handleSubmit = async (values: any) => {
    const { idcardpics } = values;
    const pics = idcardpics
      ?.filter((item: any) => {
        return item?.response?.success || item?.status === "done";
      })
      ?.map((item: any) => item?.response?.result?.savename || item?.url)
      ?.join(",")
      ?.replace(imgConfig?.url, "");
    if (!pics) {
      message.info("请先上传身份证正反面");
      return;
    }
    const params = {
      ...values,
      position: values?.position?.join(","),
      onboard_time: dayjs(values?.onboard_time)?.unix(),
      id: currentType === "edit" ? values?.id : undefined,
      idcardpics: pics,
    };
    const res =
      currentType === "edit"
        ? await updateStaff(params)
        : await addStaff(params);
    if (res?.success) {
      setOpen(false);
      message.success(currentType === "edit" ? "编辑" : "添加成功");
      actionRef?.current?.reload();
      setFileList([])
      form.setFieldValue('idcardpics', '')
    } else {
      message.error("操作失败，请联系管理员");
    }
  };
  const handleEdit = (record: any) => {
    setCurrentData(record);
    setOpen(true);
    setCurrentType("edit");
  };
  const handleViewDetail = (record: any) => {
    setCurrentData(record);
    setOpen(true);
    setCurrentType("details");
  };
  const handleCreate = () => {
    setOpen(true);
    setCurrentType("create");
  };

  return (
    <>
      <ProTable
        actionRef={actionRef}
        columns={columns as any}
        request={getStafflist}
        rowKey="employeeId"
        pagination={{ pageSize: 10 }}
        options={false}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleCreate}>
            新建员工档案
          </Button>,
        ]}
      />
      <DrawerForm
        onOpenChange={(open) => {
          if (!open) {
            setCurrentData(null);
            form.resetFields();
            setFileList([]);
          }
        }}
        title={
          currentType === "details"
            ? "查看详情"
            : currentType === "edit"
            ? "编辑员工信息"
            : "新增员工"
        }
        width={400}
        form={form}
        open={open}
        disabled={currentType === "details"}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setOpen(false),
        }}
        onFinish={handleSubmit}
        initialValues={{
          status: 1,
          onboard_time: dayjs().format("YYYY-MM-DD"),
        }}
      >
        {/* 姓名 */}
        <ProFormText
          name="name"
          label="姓名"
          width="md"
          rules={[
            { required: true, message: "请输入姓名" },
            { max: 10, message: "姓名不超过10字符" },
          ]}
          placeholder="请输入员工姓名"
        />
        <ProFormText name="id" label="id" width="md" hidden />

        {/* 性别 */}
        <ProFormSelect
          name="sex"
          label="性别"
          width="md"
          options={[
            {
              label: "男",
              value: 1,
            },
            {
              label: "女",
              value: 2,
            },
          ]}
          rules={[{ required: true, message: "请选择性别" }]}
        />

        {/* 身份证号 */}
        <ProFormText
          name="idcard"
          label="身份证号"
          width="md"
          rules={[
            { required: true, message: "请输入身份证号" },
            { len: 18, message: "身份证号必须为18位" },
          ]}
          placeholder="18位身份证号码"
        />

        {/* 职位 */}
        <ProFormSelect
          mode="tags"
          fieldProps={{
            maxCount: 1,
          }}
          options={[
            {
              label: "普通员工",
              value: "普通员工",
            },
            {
              label: "冲压工",
              value: "冲压工",
            },
            {
              label: "采购员",
              value: "采购员",
            },
            {
              label: "工程师",
              value: "工程师",
            },
            {
              label: "文员",
              value: "文员",
            },
            {
              label: "仓管",
              value: "仓管",
            },
          ]}
          name="position"
          label="职位"
          width="md"
          rules={[{ required: true, message: "请输入职位名称" }]}
          placeholder="请输入职位名称"
        />

        {/* 入职日期 */}
        <ProFormDatePicker
          name="onboard_time"
          label="入职日期"
          fieldProps={{
            format: "YYYY-MM-DD", // 设置日期格式
            placeholder: "请选择入职日期",
          }}
          width="md"
          rules={[{ required: true, message: "请选择入职日期" }]}
        />
        {/* 联系电话 */}
        <ProFormText
          name="phone"
          label="联系电话"
          width="md"
          rules={[
            { required: true, message: "请输入联系电话" },
            { pattern: /^1[3-9]\d{9}$/, message: "手机号格式错误" },
          ]}
          placeholder="11位手机号码"
        />

        {/* 状态 */}
        <ProFormSelect
          name="status"
          label="状态"
          width="md"
          options={[
            {
              label: "在职",
              value: 1,
            },
            {
              label: "离职",
              value: 0,
            },
          ]}
          rules={[{ required: true, message: "请选择员工状态" }]}
        />
        {/* idcardpics  */}
        <ProFormUploadButton
          fieldProps={{
            fileList,
            // accept: 'jpeg,jpg,png',
            listType: "picture-card",
            // onPreview: handlePreview,
            onChange: ({ fileList: newList }) => setFileList(newList),
          }}
          required
          rules={[{
            required: true
          }]}
          name="idcardpics"
          label="上传身份证正反面"
          action={uploadUrl}
        />
      </DrawerForm>
    </>
  );
};

export default EmployeeInfoForm;
